package com.sfac.springboot.springboot.fillter;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

@WebFilter
public class ParamFilter implements Filter {
    public static final Logger LOGGER = LoggerFactory.getLogger(ParamFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("------- init log  listener--------");
    }

    @Override
    public void destroy() {
        LOGGER.debug("------- destroy log  listener--------");
    }

    @Override
    public void doFilter(
            ServletRequest servletRequest,
            ServletResponse servletResponse,
            FilterChain chain) throws IOException, ServletException {
        LOGGER.debug("==== Do filter ====");

        //将 ServletRequest等转化为HttpServletRequest等
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;

        //因为 HttpServletRequest不能直接操作 parameterMap，所以构建 wapper对象来进行操作
        HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(req){

            //重写 wrapper对象的 getParameter方法，替换掉脏字符串
            @Override
            public String getParameter(String name) {
                String value = super.getParameter(name);
                return StringUtils.isNotBlank(value) ?
                value.replaceAll("fuck","xxxx") : "";
            }

            @Override
            public String[] getParameterValues(String name) {
                String[] values = super.getParameterValues(name);
                if (values == null){
                    return new String[]{};
                }
                return Arrays.asList(values)
                        .stream()
                        .map(item->item.replaceAll("fuck","xxx"))
                        .toArray(String[]::new);
            }
        };

        //将 wapper和 response对象交出去
        chain.doFilter(wrapper,res);
    }
}
